package com.ff.neuropp.controller;

import com.ff.neuropp.util.FileUtils;
import com.ff.neuropp.util.ResultTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;


@RestController
@RequestMapping("/api/file")
@Api(value = "通用文件上传controller", tags = {"通用文件上传接口"})
public class FileUploadController {

    @ApiOperation(value = "单文件上传", notes = "单文件上传")
    @PostMapping(value = "/upload")
    public Map<String,Object> upload(@ApiParam(value = "文件",required = true) @RequestParam("file") MultipartFile file, HttpServletRequest request){
        if(file.isEmpty()){
            return ResultTool.genFailResult(ResultTool.ErrorCode_1,"至少选择一个文件");
        }
        Map<String,Object> data = new HashMap<>();
        String originalfileName = file.getOriginalFilename();
        String fileUrl = null;
        try {
            fileUrl = FileUtils.upload(file.getInputStream(),"",originalfileName);
            if(StringUtils.isEmpty(fileUrl)){
                return ResultTool.genFailResult(ResultTool.ErrorCode_1,"上传失败");
            }
        } catch (IOException e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1,"上传失败");
        }
        data.put("fileName",originalfileName);
        data.put("fileUrl",fileUrl);
        return ResultTool.genSuccessResult(data);
    }



//    @ApiOperation(value = "文件批量上传", notes = "文件批量上传")
//    @PostMapping(value = "/batchUpload")
//    public Map<String,Object> batchUpload(@ApiParam(value = "文件列表",required = true) @RequestParam("files") MultipartFile[] files,HttpServletRequest request){
//        if(files==null || files.length==0){
//            return ResultTool.genFailResult(ResultTool.ErrorCode_1,"至少选择一个文件");
//        }
//        List<Map<String,Object>> data = new ArrayList<>();
//        Arrays.asList(files).forEach(file->{
//            Map<String,Object> map = new HashMap<>();
//            map.put("fileName",file.getOriginalFilename());
//            map.put("fileUr","");
//            data.add(map);
//        });
//        return ResultTool.genSuccessResult(data);
//    }
}
